package com.monitoring.domain.service;

import com.monitoring.domain.entity.Device;
import com.monitoring.domain.entity.EnvironmentalData;
import com.monitoring.domain.entity.Sensor;
import com.monitoring.domain.repository.DeviceRepository;
import com.monitoring.domain.repository.EnvironmentalDataRepository;
import com.monitoring.domain.repository.SensorRepository;
import com.monitoring.domain.valueobject.Temperature;
import com.monitoring.domain.valueobject.Humidity;
import com.monitoring.domain.valueobject.EnergyConsumption;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EnvironmentalMonitoringService {
    private final EnvironmentalDataRepository dataRepository;
    private final SensorRepository sensorRepository;
    private final DeviceRepository deviceRepository;
    
    public EnvironmentalMonitoringService(EnvironmentalDataRepository dataRepository,
                                         SensorRepository sensorRepository,
                                         DeviceRepository deviceRepository) {
        this.dataRepository = dataRepository;
        this.sensorRepository = sensorRepository;
        this.deviceRepository = deviceRepository;
    }
    
    // 记录环境数据
    public EnvironmentalData recordEnvironmentalData(Long sensorId, double temperatureValue,
                                                   double humidityValue, double energyValue,
                                                   String dataType) {
        // 验证传感器存在且活跃
        Sensor sensor = sensorRepository.findById(sensorId)
                .orElseThrow(() -> new IllegalArgumentException("传感器不存在"));
        
        if (!sensor.isActive()) {
            throw new IllegalArgumentException("传感器未激活");
        }
        
        // 创建环境数据记录
        EnvironmentalData data = new EnvironmentalData();
        data.setSensor(sensor);
        data.setTemperatureValue(temperatureValue);
        data.setHumidityValue(humidityValue);
        data.setEnergyValue(energyValue);
        data.setDataType(dataType);
        
        // 数据验证
        if (data.isTemperatureOutOfRange()) {
            throw new IllegalArgumentException("温度值超出有效范围");
        }
        if (data.isHumidityOutOfRange()) {
            throw new IllegalArgumentException("湿度值超出有效范围");
        }
        if (data.isEnergyNegative()) {
            throw new IllegalArgumentException("能耗值不能为负数");
        }
        
        // 保存数据
        return dataRepository.save(data);
    }
    
    // 根据传感器ID获取环境数据
    public List<EnvironmentalData> getEnvironmentalDataBySensorId(Long sensorId) {
        return dataRepository.findBySensorId(sensorId);
    }
    
    // 根据位置获取环境数据
    public List<EnvironmentalData> getEnvironmentalDataByLocation(String location) {
        return dataRepository.findByLocation(location);
    }
    
    // 获取特定时间段的环境数据
    public List<EnvironmentalData> getEnvironmentalDataByTimeRange(LocalDateTime start,
                                                                 LocalDateTime end) {
        return dataRepository.findByTimestampBetween(start, end);
    }
    
    // 获取传感器最新的环境数据
    public List<EnvironmentalData> getLatestEnvironmentalData(Long sensorId, String dataType, int limit) {
        return dataRepository.findLatestBySensorAndType(sensorId, dataType, limit);
    }
    
    // 处理温度过高的情况（示例方法）
    public void handleHighTemperature(Long sensorId, double temperature) {
        Temperature temp = new Temperature(temperature, "Celsius");
        if (temp.isHigh()) {
            // 查找该位置的空调设备
            Sensor sensor = sensorRepository.findById(sensorId)
                    .orElseThrow(() -> new IllegalArgumentException("传感器不存在"));
            
            List<Device> airConditioners = deviceRepository.findByLocation(sensor.getLocation());
            for (Device device : airConditioners) {
                if (device.getType().equals("AIR_CONDITIONER") && device.isActive()) {
                    device.turnOn();
                    deviceRepository.save(device);
                }
            }
        }
    }
    
    // 计算能耗成本
    public double calculateEnergyCost(Long deviceId, double pricePerKwh) {
        Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new IllegalArgumentException("设备不存在"));
        
        if (device instanceof com.monitoring.domain.entity.ElectricMeter) {
            com.monitoring.domain.entity.ElectricMeter meter = 
                    (com.monitoring.domain.entity.ElectricMeter) device;
            
            EnergyConsumption consumption = new EnergyConsumption(
                    meter.getTotalConsumption(),
                    LocalDateTime.now(),
                    deviceId.toString()
            );
            
            return consumption.getCost(pricePerKwh);
        }
        
        throw new IllegalArgumentException("设备不是电表");
    }
}